/**
 * 
 */
package com.changil.nowonchangilchurch.widget.asyncimagegetter;

import java.util.HashMap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;

import com.changil.nowonchangilchurch.util.UrlUtil;

/**
 * @author 홍창우
 *
 */
public class HtmlSetter {
	
	private Context mContext;
	private TextView mHolder;
	private String mHtml;
	private AsyncImageGetter mImageGetter;
	private boolean mIsImageLaod = false;
	
	private static HashMap<String, Drawable> mImageMap = new HashMap<String, Drawable>();
	private HtmlSetter(Context context, TextView holder, String html, boolean isImageLoad) {
		mContext = context;
		mHolder = holder;
		mHtml = html;
		mIsImageLaod = isImageLoad;
		mImageGetter = new AsyncImageGetter();
	}
	
	public static HtmlSetter newInstanceWithImageLoad(Context context, TextView holder, String html) {
		return new HtmlSetter(context, holder, html, true);
	}
	
	public static HtmlSetter newInstanceWithoutImageLoad(Context context, TextView holder, String html) {
		return new HtmlSetter(context, holder, html, false);
	}
	
	private class AsyncImageGetter implements Html.ImageGetter {
		private final Drawable mDefaultDrawable = new ColorDrawable(0xffffffff);
		private boolean mIsDownload;
		void setDownload(boolean isDownload) {
			mIsDownload = isDownload;
		}
		//Html.fromHtml에 의해 html 문자열이 해석될때 <img>태그를 만나면 무조건 호출..
		//그리고 최종 이함수에서 리턴하는 <img>태그에 출력
		//매개변수로 <img>태그의 src 속성값을 전달해준다
		@Override
		public Drawable getDrawable(String source) {
			if(mIsImageLaod) {
				final String thumb = UrlUtil.getThumbnailUrl(source, mContext.getResources().getDisplayMetrics().widthPixels);
				Drawable drawable = mImageMap.get(thumb);
				if (drawable != null) {
					drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
					return drawable;
				} else if (mIsDownload && drawable == null) {
					HttpImageCallback callback = new HttpImageCallback() {

						@Override
						public void onResult(Bitmap d) {
							Drawable drawable = null;
							drawable = new BitmapDrawable(mContext.getResources(), d);
							mImageMap.put(thumb, drawable);
							setTextViewHTML(false);
						}
					};
					HttpImageRequester requester = new HttpImageRequester();
					requester.request(thumb, callback);
				}
			}
			return mDefaultDrawable;
		}
	}
	
	
	
	public void setTextViewHTML(boolean down) {
		mImageGetter.setDownload(down);
		mHolder.setText(Html.fromHtml(mHtml,mImageGetter,null));	
		mHolder.setMovementMethod(LinkMovementMethod.getInstance());
	}

	
}
